package com.aruba.shaderapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.SweepGradient;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * 雷达效果
 */
public class RaderView extends View {
    private int width, height, radius;
    private SweepGradient sweepGradient;
    private Paint paint = new Paint();
    private Matrix matrix = new Matrix();
    //递增的角度
    private int FACTOR = 2;
    private int RATIO = 0;
    //背景paint
    private Paint bgPaint = new Paint();

    public RaderView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setBackgroundColor(Color.BLACK);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        width = getMeasuredWidth();
        height = getMeasuredHeight();
        radius = (int) (Math.min(width, height) / 2.0f);

        sweepGradient = new SweepGradient(radius, radius, new int[]{Color.GREEN, Color.TRANSPARENT}, null);
        paint.setShader(sweepGradient);
        paint.setAntiAlias(true);

        bgPaint.setStyle(Paint.Style.STROKE);
        bgPaint.setAntiAlias(true);
        bgPaint.setColor(Color.WHITE);
        bgPaint.setStrokeWidth(2);
        bgPaint.setPathEffect(new DashPathEffect(new float[]{10, 10}, 0));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawCircle(radius, radius, radius, paint);
        drawBackGround(canvas);

        RATIO += FACTOR;
        if (RATIO == 360) {
            RATIO = 0;
        }
        matrix.setRotate(RATIO, radius, radius);
        sweepGradient.setLocalMatrix(matrix);
        postInvalidateDelayed(10);
    }

    /**
     * 画背景
     *
     * @param canvas
     */
    private void drawBackGround(Canvas canvas) {
        canvas.drawCircle(radius, radius, radius, bgPaint);
        canvas.drawCircle(radius, radius, radius / 4.0f, bgPaint);
        canvas.drawCircle(radius, radius, radius * 2.0f / 4.0f, bgPaint);
        canvas.drawCircle(radius, radius, radius * 3.0f / 4.0f, bgPaint);
        canvas.drawPoint(radius, radius, bgPaint);

        Path path_h = new Path();
        path_h.moveTo(0, radius);
        path_h.lineTo(radius * 2, radius);
        canvas.drawPath(path_h, bgPaint);

        Path path_v = new Path();
        path_v.moveTo(radius, 0);
        path_v.lineTo(radius, radius * 2);
        canvas.drawPath(path_v, bgPaint);
    }
}
